package com.sinosoft.taxbenefit.core.securityguard.biz.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.config.SystemConstants;
import com.sinosoft.platform.common.util.DateUtil;
import com.sinosoft.platform.common.util.ReflectionUtil;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.base.HXResultCodeDTO;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_DISPOSE_TYPE;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.TaxFaulTaskDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.CoreRequestHead;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ThirdSendResponseDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepBeneficiaryInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepBodyDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepCoverageInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepEndorsementInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepGroupPolicyHolderInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepInsuredInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepLiabilityInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqKeepSinglePolicyHolderInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqkeepEndorsementDTO;
import com.sinosoft.taxbenefit.api.dto.request.securityguard.ReqkeepUnderwritingInfoDTO;
import com.sinosoft.taxbenefit.api.dto.response.securityguard.ResultEndorsement;
import com.sinosoft.taxbenefit.api.dto.response.securityguard.ResultInsured;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_BUSINESS_RESULR;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RC_STATE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUUM_CODE_MAPPING;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.ReqBusinessDTO;
import com.sinosoft.taxbenefit.core.common.dto.ReqBusinessDetailDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.ebaowebservice.EndorsementService;
import com.sinosoft.taxbenefit.core.ebaowebservice.EndorsementService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContApplyPersonMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContBenefitorMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContEndorsementMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContInsuredMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContPolicyDutyMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContPolicyUwinfoMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxFaultTaskMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxPolicyRiskMapper;
import com.sinosoft.taxbenefit.core.generated.model.TaxCont;
import com.sinosoft.taxbenefit.core.generated.model.TaxContApplyPerson;
import com.sinosoft.taxbenefit.core.generated.model.TaxContBenefitor;
import com.sinosoft.taxbenefit.core.generated.model.TaxContEndorsement;
import com.sinosoft.taxbenefit.core.generated.model.TaxContGroupApplyPerson;
import com.sinosoft.taxbenefit.core.generated.model.TaxContInsured;
import com.sinosoft.taxbenefit.core.generated.model.TaxContPolicyDuty;
import com.sinosoft.taxbenefit.core.generated.model.TaxContPolicyUwinfo;
import com.sinosoft.taxbenefit.core.generated.model.TaxFaultTask;
import com.sinosoft.taxbenefit.core.generated.model.TaxPolicyRisk;
import com.sinosoft.taxbenefit.core.policy.biz.service.PolicyService;
import com.sinosoft.taxbenefit.core.securityguard.biz.service.PreservationOfChangeService;
import com.sinosoft.taxbenefit.core.securityguard.config.CORE_ENUM_ENDORSEMENT_TYPE;
import com.sinosoft.taxbenefit.core.securityguard.config.ENUM_POLICY_TYPE;
import com.sinosoft.taxbenefit.core.securityguard.dto.BeneficiaryInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.CoverageInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.EBodyResult;
import com.sinosoft.taxbenefit.core.securityguard.dto.EndorsementBody;
import com.sinosoft.taxbenefit.core.securityguard.dto.EndorsementInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.EndorsementResult;
import com.sinosoft.taxbenefit.core.securityguard.dto.GroupPolicyHolderInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.InsuredInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.InsuredResult;
import com.sinosoft.taxbenefit.core.securityguard.dto.LiabilityInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.SinglePolicyHolderInfoDTO;
import com.sinosoft.taxbenefit.core.securityguard.dto.UnderwritingInfoDTO;
import com.sinosoft.taxbenefit.core.transCode.biz.service.TransCodeService;

@Service
public class PreservationOfChangeServiceImpl extends TaxBaseService implements PreservationOfChangeService {
	@Autowired
	private PolicyService policyService;
	@Autowired
	private FaultTaskService faultTaskService;
	@Autowired
	TaxFaultTaskMapper  taxFaultTaskMapper;//异常任务
	@Autowired
	CommonCodeService commonCodeService;
	@Autowired
	private TaxContMapper taxContMapper;// 保单
	@Autowired
	private TaxPolicyRiskMapper taxPolicyRiskMapper;// 险种
	@Autowired
	private TaxContInsuredMapper taxContInsuredMapper;// 被保人
	@Autowired
	private TaxContBenefitorMapper taxContBenefitMapper;// 受益人
	@Autowired
	private TaxContPolicyDutyMapper taxContPolicyDutyMapper;// 险种责任
	@Autowired
	private TaxContEndorsementMapper taxContEndorsementMapper;// 保全变更记录
	@Autowired
	private TaxContApplyPersonMapper taxContApplyPersonMapper;// 投保人
	@Autowired
	private TaxContPolicyUwinfoMapper taxContPolicyUwinfoMapper;// 核保
	@Autowired
	TransCodeService transCodeService;

	@Override
	public ThirdSendResponseDTO modifySecurityGuard(ReqKeepBodyDTO reqbodyDTO, ParamHeadDTO paramHead) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		try {
			List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			logger.info("保全变更信息上传（核心请求）JSON 体数据内容：" + JSONObject.toJSONString(reqbodyDTO));
			// 1.转换为中保信dto
			EndorsementInfoDTO bodydto = this.changeDTO(reqbodyDTO);
			EndorsementBody endorsement = new EndorsementBody();
			endorsement.setEndorsement(bodydto);
			// 2.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CHANGE.code(), paramHead, endorsement);
			logger.info("保全变更信息上传（请求中保信）JSON 体数据内容：" + JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			// "https://health.ciitc.com.cn:7301/datahub.ws/services/endorsement?wsdl";
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CHANGE.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			EndorsementService_Service service = new EndorsementService_Service(wsdlLocation);
			EndorsementService servicePort = service.getEndorsementServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.endorsementService(thirdSendDTO.getHead(), thirdSendDTO.getBody(), responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("保全变更信息上传(中报信返回)JSON数据内容：" + responseBody.getJsonString());
			// 封装发送报文日志对象
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHead.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CHANGE.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			// 3.封装返回核心dto;
			ResultEndorsement endorsementResult = new ResultEndorsement();
			ResultInsured insured = null;
			List<ResultInsured> insuredList = new ArrayList<ResultInsured>();
			// 业务号
			endorsementResult.setBizNo(reqbodyDTO.getEndorsement().getBizNo());
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				// 4.存储业务表数据
				this.modifyPolicyInfo(reqbodyDTO);
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				// 成功记录数
				Integer successNum = 0;
				// 失败记录数
				Integer failNum = 0;
				EBodyResult eBodyResult = JSONObject.parseObject(responseBody.getJsonString(), EBodyResult.class);
				EndorsementResult EBresult = eBodyResult.getEndorsementResult();
				// 保全编码
				endorsementResult.setEndorsementSequenceNo(EBresult.getEndorsementSequenceNo());
				if (null != EBresult.getSinglePolicyHolder()) {
					// 原投保人编码
					endorsementResult.setCustomerNo(EBresult.getSinglePolicyHolder().getCustomerNo());
					// 新投保人编码
					endorsementResult.setCustomerNoNew(EBresult.getSinglePolicyHolder().getCustomerNoNew());
					// 税优提示
					endorsementResult.setTaxWarning(EBresult.getSinglePolicyHolder().getTaxWarning());
				}
				List<InsuredResult> list = EBresult.getInsuredList();
				for (InsuredResult i : list) {
					insured = new ResultInsured();
					HXResultCodeDTO result = new HXResultCodeDTO();
					insured.setSequenceNo(i.getSequenceNo());
					insured.setCustomerNo(i.getCustomerNo());
					insured.setCustomerNoNew(i.getCustomerNoNew());
					result.setResultCode(i.getResult().getResultCode());
					StringBuffer sb = new StringBuffer();
					List<String> messagelist = i.getResult().getResultMessage();
					String message="";
					if (null != messagelist && messagelist.size() > 0) {
						for (String mess : messagelist) {
							sb.append(mess).append("|");
						}
						message = sb.substring(0, sb.length() - 1).toString();
						result.setResultMessage(message);
					}
					insured.setResult(result);
					insuredList.add(insured);
					// 成功记录计数
					if (ENUM_RESULT_CODE.SUCCESS.code().equals(i.getResult().getResultCode())) {
						successNum += 1;
					} else {
						// 失败记录计数
						failNum += 1;
						//记录失败明细				
						ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
						reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
						reqBusinessDetailDTO.setResultMessage(message);
						reqBusinessDetailList.add(reqBusinessDetailDTO);
					}
				}
				endorsementResult.setInsuredList(insuredList);
				thirdSendResponse.setResJson(endorsementResult);
				// 登记请求记录
				businessDTO.setReqSuccessNum(successNum);
				businessDTO.setReqFailNum(failNum);
			} else {
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				//记录失败明细			
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
				reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
				reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
				reqBusinessDetailList.add(reqBusinessDetailDTO);
			}
			// 添加记录失败明细
			commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
			// 添加请求交易记录数
			businessDTO.setRequetNum(responseHeader.getRecordNum());
			commonCodeService.addReqBusinessCollate(businessDTO);
		} catch (Exception e) {
			e.printStackTrace();
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			TaxFaulTaskDTO taxFaultTask = new TaxFaulTaskDTO();
			taxFaultTask.setServerPortCode(paramHead.getPortCode());
			taxFaultTask.setServerPortName(paramHead.getPortName());
			taxFaultTask.setAreaCode(paramHead.getAreaCode());
			taxFaultTask.setSerialNo(paramHead.getSerialNo());
			taxFaultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTaskService.addTaxFaultTask(taxFaultTask);
			logger.error("保全后置处理失败：" + e.getMessage());
		}
		return thirdSendResponse;
	}

	private TaxContEndorsement changeEndorsementDTO(ReqKeepEndorsementInfoDTO endorsementInfo) {
		TaxContEndorsement endor = new TaxContEndorsement();
		endor.setBizNo(endorsementInfo.getBizNo());
		endor.setContNo(endorsementInfo.getPolicyNo());
		endor.setEdorNo(endorsementInfo.getEndorsementNo());
		endor.setEdorType(endorsementInfo.getEndorsementType());
		endor.setEdorSeqNo(endorsementInfo.getPolEndSeq());
		endor.setEdorFinishDate(DateUtil.parseDate(endorsementInfo.getFinishTime()));
		endor.setEdorState(endorsementInfo.getEndorsementStatus());
		endor.setEdorAppDate(DateUtil.parseDate(endorsementInfo.getEndorsementApplicationDate()));
		endor.setEdorValidDate(DateUtil.parseDate(endorsementInfo.getEffectiveDate()));
		endor.setPaySequence(endorsementInfo.getPaymentFrequency());
		endor.setTaxDeduct(endorsementInfo.getTaxDeduct());
		endor.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		endor.setCreatorId(SystemConstants.SYS_OPERATOR);
		endor.setCreateDate(DateUtil.getCurrentDate());
		endor.setModifierId(SystemConstants.SYS_OPERATOR);
		endor.setModifyDate(DateUtil.getCurrentDate());
		return endor;
	}

	// 保单信息DTO转换
	private TaxCont changePolicyInfoDTO(ReqKeepEndorsementInfoDTO endorsementInfo) {
		TaxCont taxCont = new TaxCont();
		taxCont.setBizNo(endorsementInfo.getBizNo());
		// taxCont.setProposalNo();
		taxCont.setContNo(endorsementInfo.getPolicyNo());
		taxCont.setContType(endorsementInfo.getEndorsementType());
		taxCont.setContSource(endorsementInfo.getPolicySource());
		taxCont.setBelongedManageCode(endorsementInfo.getPolicyOrg());
		taxCont.setContArea(endorsementInfo.getPolicyArea());
		taxCont.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return taxCont;
	}
	// 封装个人投保人信息
	private TaxContApplyPerson changePolicyHolderDTO(ReqKeepSinglePolicyHolderInfoDTO policyHolder) {
		TaxContApplyPerson applyPerson = new TaxContApplyPerson();
		applyPerson.setCustomerCode(policyHolder.getCustomerNo());
		applyPerson.setName(policyHolder.getName());
		applyPerson.setGender(policyHolder.getGender());
		applyPerson.setBirthday(DateUtil.parseDate(policyHolder.getBirthday()));
		applyPerson.setCardType(policyHolder.getCertiType());
		applyPerson.setCardNo(policyHolder.getCertiNo());
		applyPerson.setNationality(policyHolder.getNationality());
		applyPerson.setTaxIndi(policyHolder.getTaxIndi());
		applyPerson.setTaxPayerType(policyHolder.getTaxPayerType());
		applyPerson.setWorkUnit(policyHolder.getWorkUnit());
		applyPerson.setTaxRegisterNo(policyHolder.getOrganCode1());
		applyPerson.setOrganCode(policyHolder.getOrganCode2());
		applyPerson.setBusinessLicenseCode(policyHolder.getOrganCode3());
		applyPerson.setSocietyCreditCode(policyHolder.getOrganCode4());
		applyPerson.setResidencePlace(policyHolder.getResidencePlace());
		applyPerson.setMobile(policyHolder.getMobileNo().toString());
		applyPerson.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return applyPerson;
	}
	// 封装团单投保信息
	private TaxContGroupApplyPerson changeGroupPolicyHolderDTO(ReqKeepGroupPolicyHolderInfoDTO policyHolder) {
		TaxContGroupApplyPerson groupApplyPerson = null;
		if (null != policyHolder) {
			groupApplyPerson = new TaxContGroupApplyPerson();
			groupApplyPerson.setCustomerNo(policyHolder.getCompanyNo());
			groupApplyPerson.setName(policyHolder.getCompanyName());
			groupApplyPerson.setInsuranceUnitTaxRegisterNo(policyHolder.getOrganCode1());
			groupApplyPerson.setOrganCode(policyHolder.getOrganCode2());
			groupApplyPerson.setBusinesslicenseCode(policyHolder.getOrganCode3());
			groupApplyPerson.setSocietyCreditCode(policyHolder.getOrganCode4());
			groupApplyPerson.setResidencePlace(policyHolder.getResidencePlace());
			groupApplyPerson.setIndustry(policyHolder.getIndustry());
			groupApplyPerson.setCompanyNature(policyHolder.getCompanyNature());
			groupApplyPerson.setEmployeeNumber(policyHolder.getEmployeeNumber());
			groupApplyPerson.setListIndi(policyHolder.getListedIndi());
			groupApplyPerson.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		}
		return groupApplyPerson;
	}
	// 被保险人
	private TaxContInsured changeInsuredInfoDTO(ReqKeepInsuredInfoDTO insuredDto) {
		TaxContInsured insured = new TaxContInsured();
		insured.setSequenceNo(insuredDto.getSequenceNo());
		insured.setCustomerNo(insuredDto.getCustomerNo());
		insured.setName(insuredDto.getName());
		insured.setGender(insuredDto.getGender());
		insured.setBirthday(DateUtil.parseDate(insuredDto.getBirthday()));
		insured.setCardNo(insuredDto.getCertiCode());
		insured.setCardType(insuredDto.getCertiType());
		insured.setNationality(insuredDto.getNationality());
		insured.setMobile(insuredDto.getMobileNo().toString());
		insured.setResidencePlace(insuredDto.getResidencePlace());
		insured.setHealthFlag(insuredDto.getHealthFlag());
		insured.setSocialCareNo(insuredDto.getSocialcareNo());
		insured.setProfessionCode(insuredDto.getJobCode());
		insured.setInsuredType(insuredDto.getInsuredType());
		insured.setMainInsuredNo(insuredDto.getMainInsuredNo());
		insured.setToInsuredRelation(insuredDto.getPhInsuredRelation());
		insured.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return insured;
	}
	// 受益人变更
	private TaxContBenefitor changeBeneficiaryDTO(ReqKeepBeneficiaryInfoDTO beneficiarydto) {
		TaxContBenefitor beneficiary = new TaxContBenefitor();
		beneficiary.setBenefitorType(beneficiarydto.getBeneficiaryType());
		beneficiary.setName(beneficiarydto.getName());
		beneficiary.setGender(beneficiarydto.getGender());
		beneficiary.setBirthday(DateUtil.parseDate(beneficiarydto.getBirthday()));
		beneficiary.setNationality(beneficiarydto.getNationality());
		beneficiary.setCardType(beneficiarydto.getCertiType());
		beneficiary.setCardNo(beneficiarydto.getCertiNo());
		beneficiary.setToInsuredRelation(beneficiarydto.getBenInsuredRelation());
		beneficiary.setPriority(beneficiarydto.getPriority());
		beneficiary.setProportion(beneficiarydto.getProportion());
		beneficiary.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return beneficiary;
	}
	private TaxPolicyRisk changeRiskDTO(ReqKeepCoverageInfoDTO coverage) {
		TaxPolicyRisk risk = new TaxPolicyRisk();
		risk.setRiskCode(coverage.getComCoverageCode());
		risk.setRiskName(coverage.getComCoverageName());
		risk.setCoveragePackageCode(coverage.getCoveragePackageCode());
		risk.setRiskFee(coverage.getRiskPremium());
		risk.setAppAge(Short.valueOf(coverage.getAgeOfInception().toString()));
		risk.setValidDate(DateUtil.parseDate(coverage.getCoverageEffectiveDate()));
		risk.setExpiredDate(DateUtil.parseDate(coverage.getCoverageExpirationDate()));
		risk.setMainFlag(coverage.getCoverageType());
		risk.setAnnualAmnt(coverage.getSa());
		risk.setAutoRenewFlag(coverage.getRenewIndi());
		risk.setRiskState(coverage.getCoverageStatus());
		risk.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return risk;
	}
	@SuppressWarnings("unused")
	private TaxContPolicyDuty changeDutyDTO(ReqKeepLiabilityInfoDTO liabdto) {TaxContPolicyDuty duty = new TaxContPolicyDuty();
		duty.setDutyCode(liabdto.getLiabilityCode());
		duty.setDutyAmnt(liabdto.getLiabilitySa());
		duty.setDutyState(liabdto.getLiabilityStatus());
		duty.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return duty;
	}

	// 核保变更
	private TaxContPolicyUwinfo changeUninfoDTO(ReqkeepUnderwritingInfoDTO underwrit) {
		TaxContPolicyUwinfo uWinfo = new TaxContPolicyUwinfo();
		uWinfo.setUwTime(DateUtil.parseDate(underwrit.getUnderwritingDate()));
		uWinfo.setUwDesipriton(underwrit.getUnderwritingDes());
		uWinfo.setUwResult(underwrit.getUnderwritingDecision());
		uWinfo.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return uWinfo;
	}

	/**
	 * 添加保全记录
	 */
	private void addPreservationOfChange(TaxContEndorsement endor) {
		taxContEndorsementMapper.insertSelective(endor);
	}
	/**
	 * 转中保信Dto
	 * @return
	 */
	private EndorsementInfoDTO changeDTO(ReqKeepBodyDTO bodyDto) {
		// 批单信息
		ReqKeepEndorsementInfoDTO reqEndorsement = bodyDto.getEndorsement();
		EndorsementInfoDTO endorsement = new EndorsementInfoDTO();
		ReflectionUtil.copyProperties(reqEndorsement, endorsement);
		// 保全状态转码
		endorsement.setEndorsementType(transCodeService.transCode(ENUUM_CODE_MAPPING.ENDORSEMENTTYPE.code(), reqEndorsement.getEndorsementType()));
		// 批单状态转码
		endorsement.setEndorsementStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.ENDORSEMENTSTATUS.code(), reqEndorsement.getEndorsementStatus()));
		// 保单状态转码
		endorsement.setPolicyStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.STATE.code(), reqEndorsement.getPolicyStatus()));
		// 交费频率转码
		endorsement.setPaymentFrequency(transCodeService.transCode(ENUUM_CODE_MAPPING.PAYMENTFREQUENCY.code(), reqEndorsement.getPaymentFrequency()));
		// 保单终止原因转码
		endorsement.setTerminationReason(transCodeService.transCode(ENUUM_CODE_MAPPING.TERMINATIONREASON.code(), reqEndorsement.getTerminationReason()));
		// 个单
		if (null != reqEndorsement.getSinglePolicyHolder()) {
			SinglePolicyHolderInfoDTO singlePolicy = new SinglePolicyHolderInfoDTO();
			ReqKeepSinglePolicyHolderInfoDTO keepSinglePolicy = reqEndorsement.getSinglePolicyHolder();
			ReflectionUtil.copyProperties(reqEndorsement.getSinglePolicyHolder(), singlePolicy);
			singlePolicy.setMobileNo(keepSinglePolicy.getMobileNo());
			singlePolicy.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(),keepSinglePolicy.getGender()));
			singlePolicy.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),keepSinglePolicy.getCertiType()));
			endorsement.setSinglePolicyHolder(singlePolicy);
		}
		// 团单
		if (null != reqEndorsement.getGroupPolicyHolder()) {
			GroupPolicyHolderInfoDTO groupPolicy = new GroupPolicyHolderInfoDTO();
			ReqKeepGroupPolicyHolderInfoDTO reqKeepGroupPolicyHolderInfo = reqEndorsement.getGroupPolicyHolder();
			ReflectionUtil.copyProperties(reqEndorsement.getGroupPolicyHolder(), groupPolicy);
			endorsement.setGroupPolicyHolder(groupPolicy);
		}
		// 被保人
		List<InsuredInfoDTO> insuredList = new ArrayList<InsuredInfoDTO>();
		if (this.checkList(reqEndorsement.getInsuredList())) {
			// 循环被保人
			for (ReqKeepInsuredInfoDTO reqInfoDTO : reqEndorsement.getInsuredList()) {
				InsuredInfoDTO insured = new InsuredInfoDTO();
				ReflectionUtil.copyProperties(reqInfoDTO, insured);
				insured.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(),reqInfoDTO.getGender()));
				insured.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),reqInfoDTO.getCertiType()));
				insured.setJobCode(transCodeService.transCode(ENUUM_CODE_MAPPING.JOBCODE.code(),reqInfoDTO.getJobCode()));
				// 受益人
				List<BeneficiaryInfoDTO> beneficiaryList = new ArrayList<BeneficiaryInfoDTO>();
				if (this.checkList(reqInfoDTO.getBeneficiaryList())) {
					// 循环受益人
					for (ReqKeepBeneficiaryInfoDTO reqBene : reqInfoDTO.getBeneficiaryList()) {
						BeneficiaryInfoDTO beneficiary = new BeneficiaryInfoDTO();
						ReflectionUtil.copyProperties(reqBene, beneficiary);
						beneficiary.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(), reqBene.getGender()));
						beneficiary.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),reqBene.getCertiType()));
						beneficiaryList.add(beneficiary);
					}
					insured.setBeneficiaryList(beneficiaryList);
				}
				// 险种
				List<CoverageInfoDTO> coverageList = new ArrayList<CoverageInfoDTO>();
				// 循环险种
				for (ReqKeepCoverageInfoDTO reqCoverage : reqInfoDTO.getCoverageList()) {
					CoverageInfoDTO coverageInfo = new CoverageInfoDTO();
					ReflectionUtil.copyProperties(reqCoverage, coverageInfo);
					coverageInfo.setCoverageType(transCodeService.transCode(ENUUM_CODE_MAPPING.MAINFLAG.code(), reqCoverage.getCoverageType()));
					coverageInfo.setCoverageStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.STATE.code(), reqCoverage.getCoverageStatus()));
					coverageInfo.setTerminationReason(transCodeService.transCode(ENUUM_CODE_MAPPING.TERMINATIONREASON.code(), reqEndorsement.getTerminationReason()));
					// 核保
					UnderwritingInfoDTO underwritingInfo = new UnderwritingInfoDTO();
					ReqkeepUnderwritingInfoDTO reqkeepUnderwritingInfo = reqCoverage.getUnderwriting();
					ReflectionUtil.copyProperties(reqkeepUnderwritingInfo, underwritingInfo);
					// 责任信息
					List<LiabilityInfoDTO> liabilityList = new ArrayList<LiabilityInfoDTO>();
					// 循环责任
					for (ReqKeepLiabilityInfoDTO reqLiability : reqCoverage.getLiabilityList()) {
						LiabilityInfoDTO liabilityInfo = new LiabilityInfoDTO();
						ReflectionUtil.copyProperties(reqLiability, liabilityInfo);
						liabilityInfo.setLiabilityStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.STATE.code(), reqLiability.getLiabilityStatus()));
						liabilityList.add(liabilityInfo);
					}
					coverageInfo.setLiabilityList(liabilityList);
					coverageInfo.setUnderwriting(underwritingInfo);
					coverageList.add(coverageInfo);
				}
				insured.setCoverageList(coverageList);
				insuredList.add(insured);
			}
		}
		endorsement.setInsuredList(insuredList);
		return endorsement;
	}

	/**
	 * 判断list是否为空
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private boolean checkList(List list) {
		return null != list && list.size() > 0;
	}
	public void modifyPolicyInfo(ReqKeepBodyDTO reqbodyDTO) {
		try {
			// 获取批单信息
			ReqKeepEndorsementInfoDTO endorsementInfo = reqbodyDTO.getEndorsement();
			// 保单个人投保信息
			ReqKeepSinglePolicyHolderInfoDTO policyHolder = endorsementInfo.getSinglePolicyHolder();
			// 保单团体投保信息
			ReqKeepGroupPolicyHolderInfoDTO groupPolicyHolder = endorsementInfo.getGroupPolicyHolder();
			// 被保险人列表
			List<ReqKeepInsuredInfoDTO> insuredlist = endorsementInfo.getInsuredList();
			// 保全类型
			String changeType = endorsementInfo.getEndorsementType();
			// 查到的保单信息
			TaxCont oldtaxcont = policyService.queryPolicyByPolicyNo(endorsementInfo.getPolicyNo());
			// 保全记录
			TaxContEndorsement endor = changeEndorsementDTO(endorsementInfo);
			if (null != oldtaxcont) {
				if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.APPLICANT_DATA_CHANGE.code())) {
					if (endorsementInfo.getPolicyType().equals(ENUM_POLICY_TYPE.SINGLE_POLICY_HOLDER.code())) {
						// 个人投保信息
						TaxContApplyPerson singlePolicyHolder = changePolicyHolderDTO(policyHolder);
						singlePolicyHolder.setContId(oldtaxcont.getSid());
						TaxContApplyPerson taxapply = policyService.queryApplyPersonInfo(policyHolder.getCustomerNo(),oldtaxcont.getSid());
						// 调用持久化
						if (null != taxapply) {
							singlePolicyHolder.setModifyDate(DateUtil.getCurrentDate());
							singlePolicyHolder.setModifierId(SystemConstants.SYS_OPERATOR);
							policyService.modifyPolicyHolder(singlePolicyHolder);
						}
					} else if (endorsementInfo.getPolicyType().equals(ENUM_POLICY_TYPE.GROUP_POLICY_HOLDER.code())) {
						// 团体投保信息
						TaxContGroupApplyPerson groupPolicyHolderdto = changeGroupPolicyHolderDTO(groupPolicyHolder);
						groupPolicyHolderdto.setContId(oldtaxcont.getSid());
						TaxContGroupApplyPerson groupApply = policyService.queryGroupApply(groupPolicyHolder.getCompanyNo(),oldtaxcont.getSid());
						// 调用持久化
						if (null != groupApply) {
							groupPolicyHolderdto.setModifyDate(DateUtil.getCurrentDate());
							groupPolicyHolderdto.setModifierId(SystemConstants.SYS_OPERATOR);
							policyService.modifyGroupPolicyApply(groupPolicyHolderdto);
						}
					}
				} else if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.APPLICANT_CHANGE.code())) { // 投保人变更
					if (endorsementInfo.getEndorsementType().equals(ENUM_POLICY_TYPE.SINGLE_POLICY_HOLDER.code())) {
						TaxContApplyPerson taxapply = policyService.queryApplyPersonInfo(policyHolder.getCustomerNo(), oldtaxcont.getSid());
						TaxContApplyPerson singlePolicyHolder = changePolicyHolderDTO(policyHolder);
						if (null != taxapply) {
							taxapply.setRcState(ENUM_RC_STATE.INVALID.getCode());
							taxapply.setModifierId(SystemConstants.SYS_OPERATOR);
							taxapply.setModifyDate(DateUtil.getCurrentDate());
							policyService.modifyPolicyHolder(taxapply);
						}
						// 添加新的投保人
						singlePolicyHolder.setContId(oldtaxcont.getSid());
						singlePolicyHolder.setCreatorId(SystemConstants.SYS_OPERATOR);
						singlePolicyHolder.setCreateDate(DateUtil.getCurrentDate());
						policyService.addPolicyHolder(singlePolicyHolder);
					} else if (endorsementInfo.getEndorsementType().equals(ENUM_POLICY_TYPE.GROUP_POLICY_HOLDER.code())){
						TaxContGroupApplyPerson groupPolicyHolderdto = changeGroupPolicyHolderDTO(groupPolicyHolder);
						TaxContGroupApplyPerson groupApply = policyService.queryGroupApply(groupPolicyHolder.getCompanyNo(), oldtaxcont.getSid());
						if (groupApply != null) {
							groupApply.setModifierId(SystemConstants.SYS_OPERATOR);
							groupApply.setModifyDate(DateUtil.getCurrentDate());
							groupApply.setRcState(ENUM_RC_STATE.INVALID.getCode());
							policyService.modifyGroupPolicyApply(groupApply);
						}
						groupPolicyHolderdto.setContId(oldtaxcont.getSid());
						groupPolicyHolderdto.setCreatorId(SystemConstants.SYS_OPERATOR);
						groupPolicyHolderdto.setCreateDate(DateUtil.getCurrentDate());
						policyService.addGroupPolicyApply(groupPolicyHolderdto);
					}
				// 被保险人变更
				}else if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.INSURED_DATA_CHANGE.code())
						|| changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.INSURED_BIRTHDAY_GENDER_CHANGE.code())) {
					if (null != insuredlist) {
						for (ReqKeepInsuredInfoDTO insureddto : insuredlist) {
							TaxContInsured insure = changeInsuredInfoDTO(insureddto);
							insure.setContId(oldtaxcont.getSid());
							TaxContInsured contInsured = policyService.queryInsuredInfo(insureddto.getCustomerNo(),oldtaxcont.getSid());
							// 调用持久化
							if (null != contInsured) {
								insure.setModifierId(SystemConstants.SYS_OPERATOR);
								insure.setModifyDate(DateUtil.getCurrentDate());
								insure.setSid(contInsured.getSid());
								policyService.modifyPolicyInsured(insure);
							}
						}
					}
				}else if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.BENEFICIARY_DATA_CHANGE.code())) {			// 受益人变更
					for (ReqKeepInsuredInfoDTO insureddto : insuredlist) {
						List<ReqKeepBeneficiaryInfoDTO> beneficiarylist = insureddto.getBeneficiaryList();
						for (ReqKeepBeneficiaryInfoDTO b : beneficiarylist) {
							TaxContBenefitor beneficiary = changeBeneficiaryDTO(b);
							beneficiary.setContId(oldtaxcont.getSid());
							TaxContBenefitor benef = policyService.queryBeneficiary(b.getCertiNo(),oldtaxcont.getSid());
							// 持久化
							if (null != benef) {
								beneficiary.setModifierId(SystemConstants.SYS_OPERATOR);
								beneficiary.setModifyDate(DateUtil.getCurrentDate());
								beneficiary.setSid(benef.getSid());
								policyService.modifyPolicyBeneficicary(beneficiary);
							} else {
								beneficiary.setContId(oldtaxcont.getSid());
								beneficiary.setCreatorId(SystemConstants.SYS_OPERATOR);
								beneficiary.setCreateDate(DateUtil.getCurrentDate());
								policyService.addBeneficiary(beneficiary);
							}
						}
					}
				}else if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.ADD_RISK.code())) {			// 增加险种
					for (ReqKeepInsuredInfoDTO insureddto : insuredlist) {
						List<ReqKeepCoverageInfoDTO> coveragelist = insureddto.getCoverageList();
						for (ReqKeepCoverageInfoDTO coverage : coveragelist) {
							TaxPolicyRisk risk = changeRiskDTO(coverage);
							risk.setContId(oldtaxcont.getSid());
							TaxPolicyRisk policyRisk = policyService.queryRiskInfo(coverage.getComCoverageCode(),oldtaxcont.getSid());
							// 调持久化
							if (null != policyRisk) {
								risk.setModifierId(SystemConstants.SYS_OPERATOR);
								risk.setModifyDate(DateUtil.getCurrentDate());
								risk.setSid(policyRisk.getSid());
								policyService.modifyCoverage(risk);
							} else {
								risk.setContId(oldtaxcont.getSid());
								risk.setCreatorId(SystemConstants.SYS_OPERATOR);
								risk.setCreateDate(DateUtil.getCurrentDate());
								policyService.addCoverage(risk);
							}
						}
					}
				}else if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.REDUCE_RISK.code())) {			// 减少险种
					for (ReqKeepInsuredInfoDTO insureddto : insuredlist) {
						List<ReqKeepCoverageInfoDTO> coveragelist = insureddto.getCoverageList();
						for (ReqKeepCoverageInfoDTO coverage : coveragelist) {
							TaxPolicyRisk risk = changeRiskDTO(coverage);
							risk.setContId(oldtaxcont.getSid());
							TaxPolicyRisk policyRisk = policyService.queryRiskInfo(coverage.getComCoverageCode(), oldtaxcont.getSid());
							// 调持久化
							if (null != policyRisk) {
								risk.setModifierId(SystemConstants.SYS_OPERATOR);
								risk.setModifyDate(DateUtil.getCurrentDate());
								risk.setSid(policyRisk.getSid());
								policyService.modifyCoverage(risk);
							} else {
								risk.setContId(oldtaxcont.getSid());
								risk.setCreatorId(SystemConstants.SYS_OPERATOR);
								risk.setCreateDate(DateUtil.getCurrentDate());
								policyService.addCoverage(risk);
							}
						}
					}
				}else if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.POLICY_SECOND_UNDERWRITING.code())) {			// 险种2次核保
					for (ReqKeepInsuredInfoDTO insureddt : insuredlist) {
						List<ReqKeepCoverageInfoDTO> coveragelist = insureddt.getCoverageList();
						for (ReqKeepCoverageInfoDTO coverage : coveragelist) {
							// 所属险种
							TaxPolicyRisk risk = policyService.queryRiskInfo(coverage.getComCoverageCode(), oldtaxcont.getSid());
							// 核保
							ReqkeepUnderwritingInfoDTO underwrit = coverage.getUnderwriting();
							TaxContPolicyUwinfo uw = changeUninfoDTO(underwrit);
							// 调用持久化
							uw.setPolId(risk.getSid());
							uw.setCreatorId(SystemConstants.SYS_OPERATOR);
							uw.setCreateDate(DateUtil.getCurrentDate());
							policyService.addUnderwriting(uw);
						}
					}
				}else if (changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.HESITATE_SURRENDER.code()) || changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.SURRENDER.code())
						|| changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.PROTOCOL_CANCEL.code()) || changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.CANCEL_POLICY.code())
						|| changeType.equals(CORE_ENUM_ENDORSEMENT_TYPE.BREAK_CONTRACT.code())) {			// 退保
					TaxCont taxCont = changePolicyInfoDTO(endorsementInfo);
					taxCont.setSid(oldtaxcont.getSid());
					taxCont.setRcState(ENUM_RC_STATE.INVALID.getCode());
					taxCont.setModifyDate(DateUtil.getCurrentDate());
					taxCont.setModifierId(SystemConstants.SYS_OPERATOR);
					// 调用持久化
					policyService.modifyPolicy(taxCont);
				}
				endor.setContId(oldtaxcont.getSid());// 保单Id
			}
			this.addPreservationOfChange(endor);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("保全持久化失败"+e.getMessage());	
		}
	}

	/**
	 * 保全异常任务接口
	 */
	@Override
	public ThirdSendResponseDTO modifySecurityExceptionJob(String reqJSON, String portCode, TaxFaultTask faultTask) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		try {
			List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			ParamHeadDTO paramHead = new ParamHeadDTO();
			CoreRequestHead coreRequestHead = new CoreRequestHead();
			ReqkeepEndorsementDTO reqObject = JSONObject.parseObject(reqJSON, ReqkeepEndorsementDTO.class);
			ReqKeepBodyDTO reqbodyDTO = (ReqKeepBodyDTO) reqObject.getBody();
			coreRequestHead = reqObject.getRequestHead();
			paramHead.setPortCode(portCode);
			paramHead.setAreaCode(coreRequestHead.getAreaCode());
			paramHead.setRecordNum(coreRequestHead.getRecordNum());
			paramHead.setSerialNo(coreRequestHead.getSerialNo());
			logger.info("异常任务-保全变更信息上传（核心请求）JSON 体数据内容：" + JSONObject.toJSONString(reqbodyDTO));
			// 1.转换为中保信dto
			EndorsementInfoDTO bodydto = this.changeDTO(reqbodyDTO);
			// 最外层｛｝
			EndorsementBody endorsement = new EndorsementBody();
			endorsement.setEndorsement(bodydto);
			// 2.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CHANGE.code(), paramHead, endorsement);
			logger.info("异常任务-保全变更信息上传（请求中保信）JSON 体数据内容：" + JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.SERCURITY_CHANGE.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			EndorsementService_Service service = new EndorsementService_Service(wsdlLocation);
			EndorsementService servicePort = service.getEndorsementServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.endorsementService(thirdSendDTO.getHead(), thirdSendDTO.getBody(), responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("异常任务-保全变更信息上传(中报信返回)JSON数据内容：" + responseBody.getJsonString());
			// 封装发送报文日志对象
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 3.封装返回核心dto;
			ResultEndorsement endorsementResult = new ResultEndorsement();
			ResultInsured insured = null;
			List<ResultInsured> insuredList = new ArrayList<ResultInsured>();
			// 业务号
			endorsementResult.setBizNo(reqbodyDTO.getEndorsement().getBizNo()); 
			// 初始化头部错误信息
			String messageBody = ENUM_BZ_RESPONSE_RESULT.FAIL.description();
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				// 4.存储业务表数据
				modifyPolicyInfo(reqbodyDTO);
			}else if(ENUM_RESULT_CODE.REQ_AWAIT.code().equals(responseHeader.getResultCode())){
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = messageBody = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
				faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			}
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				// 成功记录数
				Integer successNum = 0;
				// 失败记录数
				Integer failNum = 0;
				EBodyResult eBodyResult = JSONObject.parseObject(responseBody.getJsonString(), EBodyResult.class);
				EndorsementResult EBresult = eBodyResult.getEndorsementResult();
				// 保全编码
				endorsementResult.setEndorsementSequenceNo(EBresult.getEndorsementSequenceNo());
				if (null != EBresult.getSinglePolicyHolder()) {
					// 原投保人编码
					endorsementResult.setCustomerNo(EBresult.getSinglePolicyHolder().getCustomerNo());
					// 新投保人编码
					endorsementResult.setCustomerNoNew(EBresult.getSinglePolicyHolder().getCustomerNoNew());
					// 税优提示
					endorsementResult.setTaxWarning(EBresult.getSinglePolicyHolder().getTaxWarning());
				}
				List<InsuredResult> list = EBresult.getInsuredList();
				for (InsuredResult i : list) {
					insured = new ResultInsured();
					HXResultCodeDTO result = new HXResultCodeDTO();
					insured.setSequenceNo(i.getSequenceNo());
					insured.setCustomerNo(i.getCustomerNo());
					insured.setCustomerNoNew(i.getCustomerNoNew());
					result.setResultCode(i.getResult().getResultCode());
					StringBuffer sb = new StringBuffer();
					List<String> messagelist = i.getResult().getResultMessage();
					String message ="";
					if (null != messagelist && messagelist.size() > 0) {
						for (String mess : messagelist) {
							sb.append(mess).append("|");
						}
						message = sb.substring(0, sb.length() - 1).toString();
						result.setResultMessage(message);
					}
					insured.setResult(result);
					insuredList.add(insured);
					// 成功记录计数
					if (ENUM_RESULT_CODE.SUCCESS.code().equals(i.getResult().getResultCode())) {
						successNum += 1;
					} else {
						// 失败记录计数
						failNum += 1;
						ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
						reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
						reqBusinessDetailDTO.setResultMessage(message);
						reqBusinessDetailList.add(reqBusinessDetailDTO);
					}
				}
				endorsementResult.setInsuredList(insuredList);
				thirdSendResponse.setResJson(endorsementResult);
				// 登记请求记录
				businessDTO.setReqSuccessNum(successNum);
				businessDTO.setReqFailNum(failNum);
			} else {
				thirdSendResponse.setResJson(messageBody);
				//记录失败明细			
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
				reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
				reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
				reqBusinessDetailList.add(reqBusinessDetailDTO);
			}
			// 添加记录失败明细
			commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
			// 添加请求交易记录数
			businessDTO.setRequetNum(responseHeader.getRecordNum());
			commonCodeService.addReqBusinessCollate(businessDTO);
			faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("异常任务-保全后置处理失败：" + e.getMessage());
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
			faultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
		} finally{
			faultTask.setSuccessMessage(JSONObject.toJSONString(thirdSendResponse));
			faultTask.setDisposeDate(DateUtil.getCurrentDate());
			taxFaultTaskMapper.updateByPrimaryKeySelective(faultTask);
		}
		return thirdSendResponse;
	}
}
